package com.zhupf.binaryTree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhupf
 * @date 2023年11月24日 13:33
 * @Description
 *
 * 94. 二叉树的中序遍历
 */
public class InorderTraversal {

    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        result.addAll(inorderTraversal1(root.left));
        result.addAll(inorderTraversal1(root.right));
        result.add(root.val);
        return result;
    }


    /**
     * 中序遍历
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal12(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stk = new LinkedList<TreeNode>();
        while (root != null || !stk.isEmpty()){
            while (root != null){
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }

    /**
     * 前序遍历
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal13(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stk = new LinkedList<TreeNode>();
        while (root != null || !stk.isEmpty()){
            while (root != null){
                res.add(root.val);
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            root = root.right;
        }
        return res;
    }

    /**
     * 后续遍历
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal14(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stk = new LinkedList<TreeNode>();
        while (root != null || !stk.isEmpty()){
            while (root != null && root.left != null){
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            res.add(root.left.val);
            if(root.right != null){
                stk.push(root.right);
            }else {
                res.add(root.val);
            }
        }
        return res;
    }
}
